<template>
  <div>
    <!-- <el-breadcrumb class="title">
      <el-breadcrumb-item>二维码管理</el-breadcrumb-item>
    </el-breadcrumb> -->

      <div class="bigboxTop">
        <div class="boxLeft">
          <el-input
            clearable
            placeholder="请输入考试名称"
            v-model="QRname"
          ></el-input>
          <el-cascader
            clearable
            placeholder="请选择区县"
            v-model="areavalue"
            :options="Eoptions"
            :props="optionProps"
            @change="handleChange"
          ></el-cascader>
        </div>
        <div class="boxRight">
          <el-button type="primary" @click="search()">查询</el-button>
          <el-button @click="reset()">重置</el-button>
        </div>
      </div>
      <div class="QRbut">
        <el-button @click="QR()">生成试卷</el-button>
        <el-button @click="del()" style="margin-left: 20px;">批量删除</el-button>
      </div>


    <div class="QRtb">
      <el-table
        :data="tableData"
        border
        ref="multipleTable"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        :header-cell-style="{
          background: '#f0f7fe',
          color: '#467ee1',
          fontSize: '16px',
        }"
      >
        <el-table-column type="selection" align="center" width="55">
        </el-table-column>
        <el-table-column label="序号" align="center" width="80">
          <template slot-scope="{ $index }">
            {{ startIndex + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="examName" align="center" label="试卷名称" min-width="100">
        </el-table-column>
        <el-table-column
          prop="fullName"
          align="center"
          label="试卷生成人"
          width="120"
        >
        </el-table-column>
        <el-table-column prop="major" align="center" label="专业" min-width="100">
        </el-table-column>
        <el-table-column
          prop="startTime"
          label="试卷有效开始时间"
          align="center"
          width="200"
          :formatter="formatDate"
        >
        </el-table-column>
        <el-table-column
          prop="endTime"
          align="center"
          label="试卷有效结束时间"
          width="200"
          :formatter="formatDate"
        >
        </el-table-column>
        <el-table-column prop="area" align="center" label="所属区域" min-width="100">
        </el-table-column>
        <el-table-column prop="position" align="center" label="人员类别" min-width="100">
        </el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          label="试卷创建时间"
          width="200"
          :formatter="formatDate"
        >
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="200">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small"
              >查看试卷</el-button
            >
            <el-button @click="handle(scope.row)" type="text" size="small"
              >生成试卷</el-button
            >
            <el-button @click="handleDelete(scope.row)" type="text" size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalItems"
      >
      </el-pagination>
    </div>

    <el-dialog
      title="新增试卷"
      :visible.sync="dialogTableVisible"
      customClass="customWidth"
    > 
      <el-row type="flex" justify="center">
        <el-col :span="18">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="auto" class="demo-ruleForm">
          <el-form-item label="试卷名称" prop="name" style="width: 510px;">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="试卷时间" prop="examhour">
            <el-input v-model="ruleForm.examhour" style="width: 50px;"></el-input>时 <el-input
              v-model="ruleForm.examsecond" style="width: 50px;"></el-input>分
          </el-form-item>
          <el-form-item label="试卷有效时间" required>
            <el-col :span="20">
              <el-date-picker type="datetimerange" placeholder="选择日期" range-separator="至" v-model="ruleForm.datetime"
                start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="人员类别" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择人员类别">
              <el-option v-for="item in poOptions" :key="item.id" :label="item.positionName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属区县" prop="desc">
            <el-cascader clearable placeholder="请选择区县" v-model="ruleForm.desc" :options="Eoptions" :props="optionProps"
              @change="handleChangeform"></el-cascader>
          </el-form-item>
        </el-form>
        </el-col>
        </el-row>
        <el-row type="flex" justify="center">
        <el-col :span="18">
          <div class="buttomTable">
            <div class="Table">
              <div>题目类型：</div>
              <div>单选题</div>
              <div style="margin-left: 5px">题目数量</div>
              <el-input v-model="count1"></el-input>题
              <div style="margin-left: 5px">每题分数</div>
              <el-input v-model="countScore1"></el-input>分
              <div style="margin-left: 5px">总分</div>
              <div style="margin-left: 5px">{{ totalScore1 }}分</div>
            </div>

            <div class="Table">
              <div>题目类型：</div>
              <div>判断题</div>
              <div style="margin-left: 5px">题目数量</div>
              <el-input v-model="count2"></el-input>题
              <div style="margin-left: 5px">每题分数</div>
              <el-input v-model="countScore2"></el-input>分
              <div style="margin-left: 5px">总分</div>
              <div style="margin-left: 5px">{{ totalScore2 }}分</div>
            </div>

            <div class="Table">
              <div>题目类型：</div>
              <div>多选题</div>
              <div style="margin-left: 5px">题目数量</div>
              <el-input v-model="count3" size="small"></el-input>题
              <div style="margin-left: 5px">每题分数</div>
              <el-input v-model="countScore3"></el-input>分
              <div style="margin-left: 5px">总分</div>
              <div style="margin-left: 5px">{{ totalScore3 }}分</div>
            </div>
            <h1>合计总分：{{ totalScore1 + totalScore2 + totalScore3 }}分</h1>
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <el-dialog title="查看试卷" :visible.sync="dialogQRVisible">
      <div class="erweima">
        <img :src="imgSrc" alt="" />
      </div>
      <span class="QRa" @click="smallhandle()" style="cursor: pointer"
        >下载{{examName}}的考试二维码</span
      >
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogQRVisible = false">取 消</el-button>
        <el-button type="primary" @click="makesure()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getmassage,
  getarea,
  PositionList,
  save,
  del,
  create,
  download,
} from "@/api/QRcode";
import { formatDate, FormatTime } from "@/utls/format";
export default {
  data() {
    return {
      startIndex: 0, //索引
      displayedData: [], // 当前页显示的数据
      currentPage: 1, // 当前页面
      pageSize: 10, // 每页显示的数据条数
      totalItems: 0, // 总数据条数
      dialogTableVisible: false, //新增二维码弹框
      dialogQRVisible: false,
      delarry: [], //删除数组
      count1: "",
      countScore1: "",
      count2: "",
      countScore2: "",
      count3: "",
      countScore3: "", //分数
      multipleSelection: [], //批量删除数组
      areavalue: [], //区县名存储
      QRname: "", //考试二维码名
      areaId: "", //地域id存储
      Eoptions: [], //区县
      delarrySingle: [], //删除
      formObj: {},
      imgSrc: "", //二维码图片文件
      QRid: "", //二维码id存储
      Time: "", //秒
      examName:"",//弹出框考试名称
      newdelarr:[],//去重数组
      optionProps: {
        value: "id",
        label: "areaName",
        children: "children",
        checkStrictly: true,
      },
      poOptions: [
        {
          id: "",
          positionName: "",
        },
      ],
      ruleForm: {
        name: "",
        specialityTab: "",
        datetime: "",
        type: "",
        desc: [],
        examhour: "",
        examsecond: "",
      },
      // options: [
      //   {
      //     value: "0",
      //     label: "单选题",
      //   },
      //   {
      //     value: "1",
      //     label: "多选题",
      //   },
      //   {
      //     value: "2",
      //     label: "判断题",
      //   },
      // ],
      rules: {
        name: [
          { required: true, message: "请输入考试名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        examhour: [
          { required: true, message: "请填写考试时间", trigger: "blur" },
        ],
        examsecond: [
          { required: true, message: "请填写考试时间", trigger: "blur" },
        ],
        datetime: [
          {
            type: "date",
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        type: [
          {
            type: "string",
            required: true,
            message: "请至少选择一个人员类别",
            trigger: "change",
          },
        ],
        desc: [{ required: true, message: "请填写所属区县", trigger: "blur" }],
      },
      tableData: [],
    };
  },
  computed: {
    totalScore1() {
      return this.count1 * this.countScore1;
    },
    totalScore2() {
      return this.count2 * this.countScore2;
    },
    totalScore3() {
      return this.count3 * this.countScore3;
    },
  },
  methods: {
    //时间格式化
    formatDate,
    //清空表单
    clearform() {
      this.ruleForm = {};
      this.count1 = "";
      this.countScore1 = "";
      this.count2 = "";
      this.countScore2 = "";
      this.count3 = "";
      this.countScore3 = "";
    },
    search() {
      this.currentPage=1
      this.getData();
      this.handleCurrentChange(1);
    }, //查询
    reset() {
      this.QRname = "";
      this.areavalue = "";
      this.getData();
      this.currentPage=1
      this.handleCurrentChange(1);
    }, //重置
    makesure() {
      this.dialogQRVisible = false;
    },
    handleClick(row) {
      this.dialogQRVisible = true;
      this.QRid = row.id;
      this.examName=row.examName;
      create(row.id).then((res) => {
        this.imgSrc = window.URL.createObjectURL(
          new Blob([res.data], { type: "image/png" })
        );
      });
    }, //生成二维码
    async handle(row) {
      await download(row.id).then((res) => {
        let content = res.data;
        let data = new Blob([content], {
          type: "image/png",
        });
        let downloadUrl = window.URL.createObjectURL(data);
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.href = downloadUrl;
        a.download = row.examName+"的二维码";
        a.click();
        window.URL.revokeObjectURL(downloadUrl);
      });
    }, //下载二维码
    async smallhandle() {
      await download(this.QRid).then((res) => {
        let content = res.data;
        let data = new Blob([content], {
          type: "image/png",
        });
        let downloadUrl = window.URL.createObjectURL(data);
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.href = downloadUrl;
        a.download = this.examName+"的二维码";
        a.click();
        window.URL.revokeObjectURL(downloadUrl);
      });
    }, //下载二维码弹出框
    handleDelete(row) {
      this.delarrySingle.push(row.id);
      this.$confirm("此操作将永久删除该信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          del(this.delarrySingle).then((res) => {
            if (res.data.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getData();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    del() {
      // this.$refs.multipleTable.selection.forEach(el => {
      //   this.delarry.push(el.id)
      // });
      // console.log(this.delarry);
      if (this.delarry.length == 0) {
        this.$message({
          type: "warning",
          message: "请选择删除内容",
        });
      } else {
        this.$confirm("此操作将永久删除该信息, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            del(this.delarry).then((res) => {
              if (res.data.status == 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                if(this.tableData.length<=this.newdelarr.length&&this.currentPage>1){
                  this.handleCurrentChange(--this.currentPage)
                  this.getData();
                }
                this.delarry = [];
                this.getData();
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    }, //批量删除
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.delarry = []
      this.multipleSelection.forEach((el) => {
        this.delarry.push(el.id);
      });
     this.newdelarr=[...new Set(this.delarry)]
    //  console.log(this.newdelarr);
    }, //获取批量数据
    QR() {
      //弹出框
      this.dialogTableVisible = true;
    },
    submitForm(formName) {
      this.Time = this.ruleForm.examhour * 3600 + this.ruleForm.examsecond * 60;
      if (
        this.count1 == "" ||
        this.countScore1 == "" ||
        this.count2 == "" ||
        this.countScore2 == "" ||
        this.count3 == "" ||
        this.countScore3 == ""
      ) {
        this.$message.error("请输入题数和分数");
        return false;
      }
      this.formObj = {
        countDown: this.Time,
        examName: this.ruleForm.name,
        majorId: localStorage.getItem("major"),
        startTime: FormatTime("yyyy-MM-dd hh:mm:ss", this.ruleForm.datetime[0]),
        endTime: FormatTime("yyyy-MM-dd hh:mm:ss", this.ruleForm.datetime[1]),
        positionId: this.ruleForm.type,
        areaId: this.ruleForm.desc,
        paperRuleDTOS: [
          {
            questionTypeId: 0,
            questionNum: Number(this.count1),
            score: Number(this.countScore1),
          },
          {
            questionTypeId: 2,
            questionNum: Number(this.count2),
            score: Number(this.countScore2),
          },
          {
            questionTypeId: 1,
            questionNum: Number(this.count3),
            score: Number(this.countScore3),
          },
        ],
      };
      // console.log(this.formObj);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log(this.formObj);
          save(this.formObj).then((res) => {
            if (res.data.status == 200) {
              // console.log(res.data.data);
              this.$message({
                message: "保存成功",
                type: "success",
              });
              this.dialogTableVisible = false;
              this.getData();
              this.clearform();
            }
          });
        } else {
          this.$message.error("保存失败");
          return false;
        }
      });
    }, //提交表单
    getData() {
      getmassage({
        examName: this.QRname,
        areaId: this.areaId,
        majorId: localStorage.getItem("major"),
        pageSize: this.pageSize,
        pageNum: this.currentPage,
      }).then((res) => {
        if ((res.data.status = 200)) {
          if (res.data.data == null) {
            this.$message({
              message: res.data.message,
              type: "warning",
            });
          } else {
            this.tableData = res.data.data.qrCodes;
            this.totalItems = res.data.data.total;
          }
        }
      });
    }, //获取数据
    handleChange(val) {
      this.areaId = val[val.length - 1];
      // console.log(this.areaId);
    },
    handleChangeform(val) {
      this.ruleForm.desc = val[val.length - 1];
      // console.log(this.ruleForm.desc);
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      // console.log(this.pageSize);
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.startIndex = (newPage - 1) * this.pageSize;
      const endIndex = this.startIndex + this.pageSize;
      // console.log(this.startIndex);
      // console.log(endIndex);
      let tableDatas = this.tableData;
      this.displayedData = tableDatas
        .slice(this.startIndex, endIndex)
        .map((row, index) => {
          return {
            ...row,
            index: this.startIndex + index + 1,
          };
        });
        this.$parent.$parent.$parent.scrollToTop()
    },
  },
  watch: {
    currentPage: function (newvalue) {
      this.getData(newvalue);
    },
    pageSize: function (newvalue) {
      this.getData(newvalue);
    },
  },
  mounted() {
    this.getData();
    getarea(0).then((res) => {
      this.Eoptions = res.data.data;
      // console.log(res.data.data);
    });
    PositionList().then((res) => {
      // console.log(res.data.data);
      this.poOptions = res.data.data;
    });
  },
};
</script>
<style lang="scss" scoped>
.el-pagination {
  margin: 25px 0;
}

.title {
  height: 50px;
  line-height: 50px;
  background-color: #f9f9f9;
  border: 1px solid #e9e9e9;
  border-radius: 5px;
  font-size: 17px;
  font-weight: bolder;
  padding: 0 20px;
}

.bigboxTop {
  width: 650px;
  height: 50px;
  // border: 1px solid red;
  display: flex;
  margin-top: 20px;
  align-items: center;

  .boxLeft {
    width: 400px;
    // border: 1px solid red;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .el-input {
      width: 190px;
  
    }

    .el-cascader {
      width: 190px;
    }
  }

  .boxRight {
    width: 200px;
    // border: 1px solid red;
    display: flex;
    align-items: center;
    .el-select {
      width: 190px;
    }

    .el-button {
      width: 80px;
      margin-left: 20px;
    }
  }
}

.QRbut {
  width: 350px;
  height: 50px;
  // border: 1px solid red;
  margin-top: 15px;
}

.QRtb {
  // width: 100%;
  // margin: 0 auto;
}

.tableFrom {
  // width: 700px;
  // height: auto;
  // border: 1px solid red;
  // margin: 0 auto;
  .el-input {
    width: 210px;
    height: 60px;
  }

  .el-date-picker {
    width: 210px;
    height: 60px;
  }
}

.buttomTable {
  // width: 800px;
  // height: 200px;
  text-align: center;
  font-weight: bolder;
  // border: 1px solid red;

  .Table {
    // max-width: 800px;
    margin: 0 auto;
    width: 550px;
    height: 50px;
    // border: 1px solid red;
    display: flex;
    align-items: center;

    .el-input {
      // margin-top: 18px;
      margin-left: 10px;
      max-width: 80px;
      min-width: 50px;
    }

    .el-select {
      margin-top: 15px;
    }
  }
}

.erweima {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;

  img {
    width: 400px;
    height: 400px;
    // border: 1px solid red;
    background-size: cover;
  }
}

.QRa {
  display: block;
  width: 100%;
  height: 30px;
  // border: 1px solid red;
  text-align: center;
  line-height: 30px;
}

:deep(.el-pager li.active) {
  color: #ffffff;
  background-color: #409eff;
}

:deep(.el-pager li:hover) {
  color: #787d83;
}
</style>
